/**
* @author Diego Gadola @ 30/01/2009 
*/
public class DiscussionWidgetActivePeopleController {
	
	private List<User> activePeople;
	private String id;
	
	/**
	* Constructor
	*/
	public DiscussionWidgetActivePeopleController() {
		id = System.currentPageReference().getParameters().get('id');
		findActivePeople();
	}
	
	/**
	*@return List<User>
	*/
	public List<User> getActivePeople() {
		findActivePeople();
		return activePeople;	
	}

	/**
	* Create a  list of active people
	*/
	public void findActivePeople() {
		activePeople = new List<User>();
		if(id != null && id != '' && id.length() == 18) {
			List<DiscussionMessage__c> lastMessages = [	SELECT	PostedBy__r.Id, PostedBy__r.Name
														FROM 	DiscussionMessage__c
														WHERE	DiscussionTopic__c = :id
														ORDER BY	PostedDate__c DESC 
														LIMIT 		999];
			
			if(lastMessages != null) {
				Map<ID, Integer> messagesPerUser = new Map<ID, Integer>();
				Map<ID, User> users = new Map<ID, User>();
				
				for (DiscussionMessage__c message : lastMessages) {
					if (users.containsKey(message.PostedBy__r.Id)) {
						messagesPerUser.put(message.PostedBy__r.Id, messagesPerUser.get(message.PostedBy__r.Id) + 1);	
					}
					else {
						users.put(message.PostedBy__r.Id, message.PostedBy__r);
						messagesPerUser.put(message.PostedBy__r.Id, 1);
					}
				}
				
				List<Integer> countMsgPerUser = messagesPerUser.values();
				countMsgPerUser.sort();
				
				Integer actives;
				if (countMsgPerUser.size() > 5) {
					actives = 5;
				}
				else {
					actives = countMsgPerUser.size();	
				}
				
				for(Integer i = 0; i < actives; i++) {
					Integer toFind = countMsgPerUser.remove(actives - 1 - i);
					for(ID id : messagesPerUser.keySet()) {
						if (messagesPerUser.get(id) == toFind) {
							messagesPerUser.remove(id);
							activePeople.add(users.get(id));
							break;	
						}	
					}
				}
			}
		}
	}
	
	
	/**
	*@return Integer
	*/
	public Integer getActivePeopleSize() {
		return activePeople.size();
	}	

}